<template>
  <div id="iqcResultLJ">
    <!-- 质控图合集 -->
    <Breadcrumb content="质控图" />
    <div class="bodyContent">
      <splitpanes class="area">
        <!-- 查询条件 -->
        <pane :size="sizeLeft">
          <div class="leftForm">
            <el-scrollbar style="height: 100%">
              <el-form :model="iqcResultForm" label-width="80px" class="form-input-m" :inline-message="true">
                <el-form-item label="工作组">
                  <SelectWorkGroup :url="'/api/rptGroup/findRptGroup'" @getSelectedId="getSelectedId"></SelectWorkGroup>
                </el-form-item>
                <el-form-item label="质控日期">
                  <el-date-picker v-model="iqcResultForm.QCDateS" type="datetime" placeholder="选择开始时间" align="right" :picker-options="pickerOptions" value-format="YYYY-MM-DD HH:mm:ss" @change="timeSelectChange"></el-date-picker>
                  <el-date-picker v-model="iqcResultForm.QCDateE" type="datetime" placeholder="选择结束时间" align="right" value-format="YYYY-MM-DD HH:mm:ss" @change="timeSelectChange" style="margin: 5px 0 0 0"></el-date-picker>
                </el-form-item>
                <!-- 仪器 -->
                <el-form-item prop="insId" label="仪器">
                  <el-scrollbar :options="{
                      overflowBehavior: {
                        x: 'hidden',
                        y: 'scroll'
                      }
                    }" v-loading="insLoading">
                    <el-radio-group v-model="iqcResultForm.insId">
                      <el-radio :label="item.id" v-for="(item, index) in insList" :key="index" @change="(val) => insChange(val, item)" border>
                        {{ item ? item.instrName : item.instrName }}
                      </el-radio>
                    </el-radio-group>
                  </el-scrollbar>
                </el-form-item>

                <el-form-item label="质控品">
                  <el-scrollbar :options="{
                      overflowBehavior: {
                        x: 'hidden',
                        y: 'scroll'
                      }
                    }" style="max-height: 240px; width: 100%" v-loading="IQCMloading">
                    <el-checkbox-group style="width: 89%" v-if="activeTab === 'Z' || activeTab === 'iqcYoudenChart'" v-model="iqcResultForm.iqcMaterialIds" @change="qcMaterialChange">
                      <el-checkbox v-for="(item, index) in materialList" :label="item.id" :key="index" border>
                        {{ getQcMaterialNameDesc(item) }}
                      </el-checkbox>
                    </el-checkbox-group>

                    <el-radio-group v-else v-model="iqcResultForm.iqcMaterialIds[0]" @change="qcMaterialChange">
                      <el-radio v-for="(item, index) in materialList" :label="item.id" :key="index" border>
                        {{ item.materialName + '(' + item.batchNum + ')' }}
                      </el-radio>
                    </el-radio-group>
                  </el-scrollbar>
                </el-form-item>

                <el-form-item label="项目">
                  <el-scrollbar :options="{
                      overflowBehavior: {
                        x: 'hidden',
                        y: 'scroll'
                      }
                    }">
                    <el-radio-group v-model="iqcResultForm.insAnsId">
                      <el-radio :label="item.id" v-for="(item, index) in materialItemList" :key="index" @change="insAnaSystemChange(item)" border>
                        {{ getItemDictNameDesc(item) }}
                        <div class="alarm-mark">
                          <el-tooltip class="tooltipItem" effect="light" placement="right" v-if="item.alarmCount > 0">
                            <template #content>
                              <el-scrollbar style="height: 500px; width: 410px">
                                <div v-html="replaceContent(item.alarmInfo)" class="tooltipItem" style="width: 410px"></div>
                              </el-scrollbar>
                            </template>
                            <el-badge :value="'警 ' + item.alarmCount" class="item" type="warning"></el-badge>
                          </el-tooltip>

                          <el-tooltip class="tooltipItem" effect="light" placement="right" v-if="item.outControlCount > 0">
                            <template #content>
                              <el-scrollbar style="height: 500px; width: 410px">
                                <div v-html="replaceContent(item.outControlInfo)" class="tooltipItem" style="width: 410px"></div>
                              </el-scrollbar>
                            </template>
                            <el-badge :value="'失 ' + item.outControlCount" class="item"></el-badge>
                          </el-tooltip>
                        </div>
                      </el-radio>
                    </el-radio-group>
                  </el-scrollbar>
                </el-form-item>
                <el-form-item label="CCV" v-if="isShowCCV">
                  <vxe-input v-model="ccv" type="number" step="0.01" min="0" clearable style="width: 100%"></vxe-input>
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" @click="handleSearchNew()"> 查询 </el-button>
                  <el-button v-if="activeTab === 'Z' || activeTab === 'LJ'" type="primary" @click="quietPrint()"> 打印 </el-button>
                  <el-button v-if="activeTab === 'Z' || activeTab === 'LJ'" type="primary" @click="previewPrint()"> 预览 </el-button>
                </el-form-item>
              </el-form>
            </el-scrollbar>
          </div>
        </pane>
        <pane :size="100 - sizeLeft">
          <el-tabs type="border-card" v-model="activeTab" @tab-click="tabClick">
            <el-tab-pane label="Z-分数图" name="Z"> </el-tab-pane>
            <el-tab-pane label="Levey-Jennings图" name="LJ"></el-tab-pane>
            <el-tab-pane label="Grubbs图" name="iqcGrubbchart"></el-tab-pane>
            <el-tab-pane label="Monica图" name="iqcMonicaChart"></el-tab-pane>
            <el-tab-pane label="Youden图" name="iqcYoudenChart"></el-tab-pane>
            <el-tab-pane label="正态分布图" name="iqcNormalDistributionChart"></el-tab-pane>
            <el-tab-pane label="累积和控制图" name="iqcCusumChart"></el-tab-pane>

            <div class="tab-content" v-if="activeTab === 'LJ' || activeTab === 'Z'">
              <Splitpanes horizontal>
                <Pane size="66">
                  <el-scrollbar height="100%">
                    <QcEChart id="qcEchart" ref="qcEchartRef"></QcEChart>
                  </el-scrollbar>
                </Pane>
                <Pane size="34">
                  <QcResultTable id="qcResultTable" ref="qcResultTableRef"></QcResultTable>
                </Pane>
              </Splitpanes>
            </div>

            <div class="tab-content" v-else-if="activeTab === 'iqcGrubbchart'">
              <QcGrubbChart ref="qcGrubbchart"></QcGrubbChart>
            </div>
            <div class="tab-content" v-else-if="activeTab === 'iqcMonicaChart'">
              <QcMonicaChart ref="qcMonicaChart"></QcMonicaChart>
            </div>
            <div class="tab-content" v-else-if="activeTab === 'iqcYoudenChart'">
              <QcYoudenChart ref="qcYoudenChart"></QcYoudenChart>
            </div>
            <div class="tab-content" v-else-if="activeTab === 'iqcNormalDistributionChart'">
              <QcNormalDistributionChart ref="qcNormalDistributionChart"></QcNormalDistributionChart>
            </div>
            <div class="tab-content" v-else-if="activeTab === 'iqcCusumChart'">
              <QcCusumChart ref="qcCusumChart"></QcCusumChart>
            </div>
          </el-tabs>
        </pane>
      </splitpanes>
      <MultiRptPreviewZk :reportList="reportList" :toggle="isPreviewRpt" :modalTitle="'质控图预览'" />
      <!-- 静默打印 -->
      <QuietPrint ref="quietPrintRef" :printParams="printParamsObj" />
    </div>
  </div>
</template>

<script setup lang="ts">
// 引入组件区 ==========
import { ref, reactive, toRefs, getCurrentInstance, onMounted } from 'vue';
import Breadcrumb from '@/components/Breadcrumb.vue';
import { Splitpanes, Pane } from 'splitpanes';
import { IsEmpty, DateToString, formatDateTime } from '@/utils/common';
import { getMonthFirstDay, getMonthLastDay } from '@/utils/TimeUtils';
import { VxeMessage, VxeNotifyType } from '@/utils/CommonMessage'; //提示框
import SelectWorkGroup from '@/views/lab_sys/lab_bus/components/SelectWorkGroup.vue'; //报告单元引入下拉组件
import QcEChart from './QcEChart.vue'; // e-charts 图
import QcResultTable from './QcResultTable.vue';
import QcGrubbChart from './QcGrubbChart.vue';
import QcMonicaChart from './QcMonicaChart.vue';
import QcNormalDistributionChart from './QcNormalDistributionChart.vue';
import QcCusumChart from './QcCusumChart.vue';
import QcYoudenChart from './QcYoudenChart.vue';
import html2canvas from 'html2canvas';
import MultiRptPreviewZk from '@/components/MultiRptPreviewZk.vue';
import QuietPrint from '@/components/QuietPrint.vue';
import { AppStore } from '@/stores/store';
let store = AppStore();

// 变量定义区
let { proxy }: any = getCurrentInstance();
const sizeLeft = ref(20); //左侧宽度
const iqcResultForm = reactive({
  rptGroup: null, //报告单元id
  rptGroupName: '',
  // selectWorkTeam: '', //选中的子工作组id
  insId: null, //仪器
  insName: '',
  materialItemId: '',
  insAnsId: null, //仪器项目
  itemDictId: null, // 报告项目id
  qcItemId: null, //项目
  ansName: '',
  iqcMaterialIds: [],
  QCDateS: null, //开始时间
  QCDateE: null //结束时间
});
const activeTab = ref('Z');
const insList: any = reactive([]); //仪器列表
const materialList: any = reactive([]); // 质控物列表
const materialItemList: any = reactive([]); // 质控物细项
const qcEchartRef: any = ref(null);
const qcGrubbchart: any = ref(null);
const qcMonicaChart: any = ref(null);
const qcResultTableRef: any = ref(null);
const qcNormalDistributionChart: any = ref(null);
const qcCusumChart: any = ref(null);
const qcYoudenChart: any = ref(null);

let chartHeight: number = ref();
let ccv = ref(null); //Monica图所需数据
let isShowCCV = ref(false); //是否显示Monica图所需的ccv数据
let IQCMloading = ref(false);
let insLoading = ref(false);
let printParamsObj = ref(null);
const isPreviewRpt = ref(false);

// 方法定义区
onMounted(() => {
  chartHeight = document.documentElement.clientHeight - 60 - 40 - 49 - 10 - 10;
  iqcResultForm.QCDateS = getMonthFirstDay();
  iqcResultForm.QCDateE = getMonthLastDay();
});

let reportList = reactive([]);
function previewPrint() {
  //先根据路由的URL获取对应的报表信息
  const url = '/api/pubReport/getReportIdByUrl';
  proxy.$http
    .get(url, { params: { url: '/' + proxy.$route.name } })
    .then((res: any) => {
      const reportId = res.data;
      isPreviewRpt.value = false;
      const candom: any = document.getElementById('qcEchart');
      html2canvas(candom).then((canvas) => {
        let saveUrl = canvas.toDataURL('image/jpeg'); //将图片元素转成base64图片
        reportList.length = 0;
        const data = {
          imgurl: saveUrl,
          IQCMaterialId: iqcResultForm.iqcMaterialIds.join(','),
          XMId: iqcResultForm.itemDictId,
          QCDateS: iqcResultForm.QCDateS,
          QCDateE: iqcResultForm.QCDateE,
          reportId: reportId,
          reportTemplateName: store.userInfo.orgName + '质控图'
        };
        reportList.push(data);
        isPreviewRpt.value = true;
      });
    })
    .catch((err: any) => {
      proxy.$alert(err, '提示');
    });
}

function quietPrint() {
  //先根据路由的URL获取对应的报表信息
  const url = '/api/pubReport/getReportIdByUrl';
  proxy.$http
    .get(url, { params: { url: '/' + proxy.$route.name } })
    .then((res: any) => {
      const reportId = res.data;
      const candom: any = document.getElementById('qcEchart');
      html2canvas(candom).then((canvas) => {
        let saveUrl = canvas.toDataURL('image/jpeg'); //将图片元素转成base64图片
        let arr = [];
        arr.push({
          ReportName: reportId,
          ReportParameters: [
            { Name: 'imgurl', Value: saveUrl },
            { Name: 'IQCMaterialId', Value: iqcResultForm.iqcMaterialIds.join(',') },
            { Name: 'XMId', Value: iqcResultForm.itemDictId },
            { Name: 'QCDateS', Value: iqcResultForm.QCDateS },
            { Name: 'QCDateE', Value: iqcResultForm.QCDateE }
          ],
          PdfPrinterSetting: { PdfPrinterCopies: 1 }
        });
        printParamsObj.value = arr;
      });
    })
    .catch((err: any) => {
      proxy.$alert(err, '提示');
    });
}

// 下拉报告单元获取报告单元id
function getSelectedId(propValue: any) {
  // 在这里执行你想要延迟执行的函数或代码
  iqcResultForm.rptGroup = propValue.value;
  iqcResultForm.insId = null;
  sltInstr = reactive({});
  iqcResultForm.insName = null;
  iqcResultForm.insAnsId = null;
  iqcResultForm.qcItemId = null;
  iqcResultForm.itemDictId = null;
  iqcResultForm.ansName = null;
  iqcResultForm.iqcMaterialIds.length = 0;

  //放入数据前清空数据
  insList.length = 0;
  materialList.length = 0;
  materialItemList.length = 0;
  setTimeout(() => {
    getInsList();
  }, 1);
}

// 获取仪器数据
function getInsList() {
  const url = '/lis/instrSetup/findLabInstrSetupList';
  proxy.$http
    .get(url, { params: { rptGroupId: iqcResultForm.rptGroup } })
    .then((res: any) => {
      if (res.data.length > 0) {
        insList.push(...res.data);
        // 默认勾选第一项
        insChange(insList[0].id, insList[0]);
      }
    })
    .catch((err: any) => {
      proxy.$alert(err, '提示');
    });
}
let sltInstr: any = reactive({});
// 勾选的仪器改变
function insChange(val, item) {
  iqcResultForm.insId = val;
  sltInstr = val;
  iqcResultForm.insName = IsEmpty(item.ins) ? '' : item.instrName;
  iqcResultForm.qcItemId = null;
  iqcResultForm.itemDictId = null;
  iqcResultForm.ansName = null;
  iqcResultForm.iqcMaterialIds.length = 0;

  //放入数据前清空数据
  materialList.length = 0;
  materialItemList.length = 0;
  // 根据仪器id获取质控物
  getQcMaterialList();
}

// 根据仪器id获取质控品
function getQcMaterialList() {  
  //放入数据前清空数据
  materialList.length = 0;
  const url = '/api/qc/qcMaterial/findMaterialListByQcDate';
  proxy.$http
    //注意此处的数据条数
    .get(url, {
      params: {
        pid: sltInstr,
        startDate: formatDateTime(iqcResultForm.QCDateS, 'yyyy-MM-dd'),
        endDate: formatDateTime(iqcResultForm.QCDateE, 'yyyy-MM-dd')
      }
    })
    .then((res: any) => {
      if (res.data.length > 0) {
        materialList.push(...res.data);
        let materialIds = materialList.map((item) => {
          return item.id;
        });

        iqcResultForm.iqcMaterialIds = [];
        if (materialList && materialList.length > 0) {
          const materialIds = materialList.map((item) => item.id);
          console.log(materialIds);

          if (activeTab.value === 'Z') {
            iqcResultForm.iqcMaterialIds = materialIds;
            // iqcResultForm.iqcMaterialIds.push(...materialIds);
          } else {
            // 默认勾选第一个
            iqcResultForm.iqcMaterialIds = materialIds;
          }
        }

        getMaterialItemList(iqcResultForm.iqcMaterialIds);
      }
    })
    .catch((err: any) => {
      console.log(err);
      VxeMessage(err, VxeNotifyType.error);
    });
}
// 质控物绑定值变化
function qcMaterialChange(item) {
  sltMaterialItem = null;
  iqcResultForm.insAnsId = null;
  iqcResultForm.qcItemId = null;
  iqcResultForm.itemDictId = null;
  iqcResultForm.ansName = null;
  if (activeTab.value === 'Z' || activeTab.value === 'iqcYoudenChart') {
    iqcResultForm.iqcMaterialIds = item;
  } else {
    iqcResultForm.iqcMaterialIds[0] = item;
  }

  materialItemList.length = 0;
  if (iqcResultForm.iqcMaterialIds.length > 0) {
    getMaterialItemList(iqcResultForm.iqcMaterialIds);
  } else {
    handleSearch();
  }
}
// 根据质控物ids 获取质控物细项
function getMaterialItemList(materialIds: any) {
  const url = '/api/qc/qcMaterialItem/findQcInstrItemListByInstrIds';
  proxy.$http
    .post(url, {
      columNameList: materialIds,
      QCDateS: iqcResultForm.QCDateS,
      QCDateE: iqcResultForm.QCDateE,
      seachValue: ''
    })
    .then((res: any) => {
      if (res.data.length > 0) {
        materialItemList.push(...res.data);
        // 默认选中第一项
        if (IsEmpty(sltMaterialItem)) {
          insAnaSystemChange(materialItemList[0]);
        } else {
          const kn = materialItemList.find((k) => k.id == sltMaterialItem.id);
          if (IsEmpty(kn)) {
            insAnaSystemChange(materialItemList[0]);
          } else {
            insAnaSystemChange(kn);
          }
        }
      }
    })
    .catch((err: any) => {
      VxeMessage(err, VxeNotifyType.error);
    });
}
let sltMaterialItem: any = null;
// 项目点击事件
function insAnaSystemChange(item) {
  sltMaterialItem = item;

  iqcResultForm.insAnsId = item.id;
  iqcResultForm.qcItemId = item.qcItemId;
  iqcResultForm.itemDictId = item.itemDictId;
  iqcResultForm.ansName = IsEmpty(materialItemList[0].itemDictName) ? '' : materialItemList[0].itemDictName;
  ccv.value = item.maxCv;
  handleSearch();
}

// 日期选择事件
function timeSelectChange() {
  getQcMaterialList();
}
function handleSearchNew() {
  materialItemList.length = 0;
  if (iqcResultForm.iqcMaterialIds.length > 0) {
    getMaterialItemList(iqcResultForm.iqcMaterialIds);
  } else {
    handleSearch();
  }
}

// 查询 参数val用来区分Z分数图和LJ图
function handleSearch() {
  proxy.$nextTick(() => {
    setShowCCV();
    if (activeTab.value === 'Z' || activeTab.value === 'LJ') {
      qcEchartRef.value?.getEchartData(activeTab, iqcResultForm, chartHeight);
      qcResultTableRef.value?.getIQCResultList(activeTab, iqcResultForm);
      qcResultTableRef.value?.getIQCMaterialsInfoAsync(activeTab, iqcResultForm);
      qcResultTableRef.value?.initQcMaterialSummary(iqcResultForm);
    } else if (activeTab.value === 'iqcGrubbchart') {
      qcGrubbchart.value?.getEchartData(iqcResultForm, chartHeight);
    } else if (activeTab.value === 'iqcMonicaChart') {
      qcMonicaChart.value?.getEchartData(iqcResultForm, chartHeight, ccv);
    } else if (activeTab.value === 'iqcNormalDistributionChart') {
      qcNormalDistributionChart.value?.getEchartData(iqcResultForm, chartHeight);
    } else if (activeTab.value === 'iqcCusumChart') {
      qcCusumChart.value?.getEchartData(iqcResultForm, chartHeight);
    } else if (activeTab.value === 'iqcYoudenChart') {
      qcYoudenChart.value?.getEchartData(iqcResultForm, chartHeight);
    }
  });
}
// #region 【tab页签切换】
function tabClick() {
  proxy.$nextTick(() => {
    if (!(activeTab.value === 'Z' || activeTab.value === 'iqcYoudenChart')) {
      let idslist = [];
      idslist.push(...iqcResultForm.iqcMaterialIds);
      iqcResultForm.iqcMaterialIds.length = 0;
      console.log(idslist);

      iqcResultForm.iqcMaterialIds.push(idslist[0]);
    }
    console.log(iqcResultForm.iqcMaterialIds);

    setShowCCV();
    if (activeTab.value === 'Z' || activeTab.value === 'LJ') {
      handleSearch();
    } else if (activeTab.value === 'iqcGrubbchart') {
      proxy.$nextTick(() => {
        qcGrubbchart.value?.getEchartData(iqcResultForm, chartHeight);
      });
    } else if (activeTab.value === 'iqcMonicaChart') {
      proxy.$nextTick(() => {
        qcMonicaChart.value?.getEchartData(iqcResultForm, chartHeight, ccv);
      });
    } else if (activeTab.value === 'iqcNormalDistributionChart') {
      proxy.$nextTick(() => {
        qcNormalDistributionChart.value?.getEchartData(iqcResultForm, chartHeight);
      });
    } else if (activeTab.value === 'iqcCusumChart') {
      proxy.$nextTick(() => {
        qcCusumChart.value?.getEchartData(iqcResultForm, chartHeight);
      });
    } else if (activeTab.value === 'iqcYoudenChart') {
      proxy.$nextTick(() => {
        qcYoudenChart.value?.getEchartData(iqcResultForm, chartHeight);
      });
    }
  });
}
// 判断是否显示ccv查询条件
function setShowCCV() {
  if (activeTab.value === 'iqcMonicaChart') {
    isShowCCV.value = true;
  } else {
    isShowCCV.value = false;
    return true;
  }
}

// 最左侧项目 radio的徽章的tooltip提示数据处理
function replaceContent(value) {
  const val = value.replace(/\n/g, '<br/>');
  return val;
}

function getQcMaterialNameDesc(item: any) {
  let descc = item.materialName;
  if (!IsEmpty(item.batchNum)) {
    descc += '(' + item.batchNum + ')';
  }

  return descc;
}

function getItemDictNameDesc(item: any) {
  let descc = item.itemDictName;
  if (!IsEmpty(item.itemEnCode)) {
    descc += '(' + item.itemEnCode + ')';
  }
  return descc;
}
</script>
<style lang="scss" scoped>
#iqcResultLJ {
  height: 100%;

  .bodyContent {
    height: calc(100% - 60px);
    .area {
      height: 100%;
      background-color: $base-white;
      .leftForm {
        height: 100%;
        .el-form {
          padding-top: 10px;
          .el-form-item {
            margin-bottom: 8px;
            .el-radio-group,
            .el-checkbox-group {
              width: 100%;
              .el-checkbox.is-bordered,
              .el-radio.is-bordered {
                // display: table;
                margin-bottom: 4px;
                margin-left: 0;
                width: 100%;
              }
              .el-radio:last-child {
                margin-right: 32px;
              }

              .el-radio {
                position: relative;

                .alarm-mark {
                  position: absolute;
                  right: 4px;
                  top: 1px;
                }
              }
            }
          }
        }
      }
    }
  }

  .el-tabs {
    height: 100%;

    :deep(.el-tabs__header) {
      margin: 0 0 15px 0;
    }

    :deep(.el-tabs__content) {
      padding: 0;
      height: calc(100% - 40px - 12px);
    }
    .tab-content {
      height: 100%;
    }
  }
}
</style>
